package com.fs.ibox.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.ibox.service.CollectionService;
import com.fs.ibox.util.BeanFactory;
import com.fs.ibox.util.ResponseDataUtil;
import com.fs.ibox.util.ResponseJSONUtil;
import com.fs.ibox.vo.ResponseData;
import com.fs.ibox.vo.Search;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "SearchServlet", value = "/SearchServlet/*")
public class SearchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());
        String path = request.getPathInfo();
        if ("/queryUserIdcoll".equals(path)){
            queryUserIdcoll(request,response);
        }


    }

    private void queryUserIdcoll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String keywords = request.getParameter("keywords");
        keywords="%"+keywords+"%";
        String state = request.getParameter("state");
        String username = request.getParameter("username");
        CollectionService bean = BeanFactory.createBean(CollectionService.class);
        List<Search> searches = bean.queryUserIdcoll(keywords, state,username);
        ResponseData responseData = ResponseDataUtil.buildOk(searches);
        ResponseJSONUtil.responseJSON(responseData,response);
    }
}
